package com.yxf.coordinatorlayoutandbehavior;

import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnTouchListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = (TextView) findViewById(R.id.dependency);
        textView.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.dependency:
                switch (event.getActionMasked()) {
                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:
                        int x = (int) event.getX() + v.getLeft();
                        int y = (int) event.getY() + v.getTop();
                        int left = x - v.getWidth() / 2;
                        int top = y - v.getHeight() / 2;
                        Log.d(TAG, "onTouch: x : " + x + " , y : " + y);
                        Log.d(TAG, "onTouch: width : " + v.getWidth() / 2 + " , height : " + v.getHeight() / 2);
                        Log.d(TAG, "onTouch: left : " + left + " , top : " + top);
                        setViewLocationInCoordinatorLayout(left, top, v);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:

                        break;
                    default:

                        break;
                }


                break;
            default:

                break;
        }


        return true;
    }

    public static void setViewLocationInCoordinatorLayout(int leftMargin, int topMargin, View child) {
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
        if (lp == null) {
            lp = new CoordinatorLayout.LayoutParams(child.getWidth(), child.getHeight());
        }
        lp.setMargins(leftMargin, topMargin, 0, 0);
        lp.gravity = Gravity.NO_GRAVITY;
        child.setLayoutParams(lp);
    }
}
